/***************************************************************************
 *   This is a part of the NextCAD Web APP.                                *
 *   Copyright (C) AMCAX, All rights reserved.                             *
 ***************************************************************************/

import {
  BaseCommand,
  CMEVENTS,
  pickedFaceData,
  pickedModelData,
} from '@amcax/base';
import { Picker3D, PickerMgr } from '@amcax/renderer';
import { eventCenterManager } from '@app-base/common/events/EventCenterManager';
import { PickInputRJSFFormat } from '@app-cad/common/components/command-form/constants';
import { PickableCommandForm } from '@app-cad/common/components/command-form/pickable';
import { useCommand } from '@app-cad/common/hooks/useCommand';
import { useTools } from '@app-cad/common/hooks/useTools';
import { previewer, userEvents } from '@app-cad/module';
import { wsApi } from '@app-cad/server';
import { FeaturedCmdDialogParams } from '@app-cad/types';
import { RJSFSchema } from '@rjsf/utils';
import { useAsyncEffect } from 'ahooks';
import i18n from 'i18next';
import { useEffect, useMemo, useState } from 'react';

type FormData = {
  model?: pickedModelData;
  face?: pickedFaceData;
  extend: boolean;
  reverse: boolean;
};

function CutterDialog({ title, onClose, props }: FeaturedCmdDialogParams) {
  const { picker } = useTools();
  const [formData, setFormData] = useState<FormData>({
    model: null,
    face: null,
    extend: false,
    reverse: false,
  });
  useEffect(() => {
    eventCenterManager.activeEventCenter.setState('array').addExit(exit);
    // 注册原始模型删除事件
    userEvents.on(CMEVENTS.MODEL_ADDED, newModelAdded);
    return () => {
      exit();
    };
  }, []);
  const getParams = () => {
    return {
      base: formData.model.idInfo.o,
      surface: formData.face.meshId,
      isExtendTool: formData.extend,
      reverse: formData.reverse,
    };
  };
  // 完成按钮disable判断
  const finishValid = useMemo(() => {
    if (formData.model && formData.face) {
      return true;
    } else {
      return false;
    }
  }, [formData]);
  useAsyncEffect(async () => {
    // const _isSameShell = formData.face && isSameShell([formData.face]);
    // if (!_isSameShell) {
    //   MessageTip.error('选择的面必须在同一个体上');
    // }
    if (formData.model && formData.face) {
      let result;
      if (props == null) {
        result = await wsApi.createCutter(getParams(), true);
      } else {
        result = await wsApi.setParams(props.shape, getParams(), true);
      }
      previewInCommand(result);
    } else {
      previewer.clear();
    }
  }, [formData]);
  useAsyncEffect(async () => {
    if (props == null) {
      return;
    }
    const { surface, reverse, isExtendTool } = props.params;
    await initEditDependency([props.baseid, surface]);
    const faceObj = picker.generatePickObjByPickID(surface) as pickedFaceData;
    const modelObj = picker.generatePickObjByPickID(
      props.baseid,
    ) as pickedModelData;
    setFormData({
      model: modelObj,
      face: faceObj,
      reverse,
      extend: isExtendTool,
    });
  }, []);
  const newModelAdded = () => {
    onClose();
    // Picker.deleteModels([interactonData.current.pickedObject.idInfo.o], true)
  };
  const handleExecute = async () => {
    if (formData.model && formData.face) {
      if (props == null) {
        await wsApi.createCutter(getParams());
      } else {
        await wsApi.setParams(props.shape, getParams());
      }
      previewer.clear();
    }
    onClose();
  };

  const exit = () => {
    eventCenterManager.activeEventCenter.setDefault();
    userEvents.off(CMEVENTS.MODEL_ADDED, newModelAdded);
    PickerMgr.getPicker<Picker3D>('3d').init();
  };
  const schema: RJSFSchema = {
    type: 'object',
    properties: {
      model: {
        type: 'string',
        title: '模型',
        format: PickInputRJSFFormat.PickModel,
      },
      face: {
        type: 'string',
        title: '切除面',
        format: PickInputRJSFFormat.PickSurface,
      },
      extend: {
        type: 'boolean',
        title: '外插延展',
        default: false,
      },
      reverse: {
        type: 'boolean',
        title: '反转方向',
        default: false,
      },
    },
  };
  const checkAndFinishDraw = async () => {
    handleExecute();
    onClose();
  };
  const { initEditDependency, initingEdit, previewInCommand } = useCommand(
    'cmd-shell',
    {
      onClose,
      dependencies: props?.params
        ? [props.params.base, props.params.surface.split(':')[0]]
        : [],
      finishDraw: checkAndFinishDraw,
    },
  );
  return (
    <PickableCommandForm
      isFormDataValid={finishValid}
      disabled={initingEdit}
      onClose={onClose}
      title={title}
      schema={schema}
      formData={formData}
      onChange={setFormData}
      extraUiSchema={{
        model: {
          'ui:placeholder': '请输入模型',
          'ui:autofocus': true,
        },
        face: {
          'ui:placeholder': '请输入平面',
          'ui:options': {
            allowInfinitePlane: true,
          },
        },
      }}
      submitText='完成'
      onSubmit={checkAndFinishDraw}
    />
  );
}

export const cmdCutter: BaseCommand = {
  id: 'CmdCutter',
  label: 'command.cutter',
  icon: 'commands/feature/cutter',
  create: (label: string, onClose: () => void, props) => (
    <CutterDialog
      title={i18n.t(label)}
      onClose={onClose}
      props={props}
      placement='topLeft'
    />
  ),
};
